import React from 'react'
import Component, { mapStateToProps, mapDispatchToProps } from '@components/Component'
import { connect } from 'react-redux'
import { Form, Row, Col, Input, Button, Table, message, DatePicker } from 'antd'
import { UpOutlined, DownOutlined } from '@ant-design/icons'
import moment from 'moment'
import { addWindow } from '@redux/actions'
import style from '../filingCaseManage/CaseManage.module.less'
import CaseNoRender from '@components/CaseNoRender'

const { Item } = Form
// const { Option } = Select

const layout = {
  labelCol: { flex: '100px' }
}

// 获取表格字段配置
function getColumns () {
  return [
    {
      title: '序号',
      dataIndex: 'key',
      key: 'index',
      align: 'center',
      width: 60
    },
    {
      title: '案号',
      dataIndex: 'caseno_desc',
      key: 'caseno_desc',
      render: (v, l) => {
        return <CaseNoRender data={l} />
      }
    },
    {
      title: '申请人',
      dataIndex: 'applicants',
      key: 'applicants',
      width: '15%',
      render: v => {
        return (v || []).filter(li => li.status).map(li => li.name).join('、')
      }
    },
    {
      title: '被申请人',
      dataIndex: 'respondents',
      key: 'respondents',
      width: '15%',
      render: v => {
        return (v || []).filter(li => li.status).map(li => li.name).join('、')
      }
    },
    {
      title: '案由',
      dataIndex: 'cause_action',
      key: 'cause_action',
      ellipsis: true
    },
    {
      title: '争议金额',
      dataIndex: 'dispute_amount',
      key: 'dispute_amount',
      render: v => {
        return String(v || 0).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
      }
    },
    {
      title: '仲裁费',
      dataIndex: 'fee',
      key: 'fee',
      render: v => {
        return String(v || 0).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
      }
    },
    {
      title: '案件状态',
      dataIndex: 'status',
      key: 'status',
      width: 80
    },
    {
      title: '立案员',
      dataIndex: 'accepter',
      key: 'accepter',
      width: 70
    },
    {
      title: '立案时间',
      dataIndex: 'docket_datetime',
      key: 'docket_datetime',
      render: v => {
        return v ? moment(v * 1000).format('YYYY-MM-DD') : ''
      }
    },
    {
      title: '操作',
      dataIndex: 'index',
      key: 'operate',
      render: (value, line) => {
        // if (line.cause_action) {
        //   return (<span className={style['operate-btn']} onClick={() => this.openDetail(line)}>详情</span>)
        // }
        return (
          <span className={style['operate-cell']}>
            <span onClick={() => this.openDetail(line)}>详情</span>
            <span onClick={() => this.toSelectSecretary(line)}>指定秘书</span>
            {/* <span onClick={() => this.fullInfo(line)}>完善信息</span> */}
          </span>
        )
      }
    }
  ]
}

class AllCaseManage extends Component {
  state = {
    searchToggleBtn: false,
    loading: false,
    list: [],
    status: '全部',
    pagination: {
      current: 1,
      pageSize: 10,
      total: 0,
      showSizeChanger: true,
      showQuickJumper: true,
      showTotal: total => `共 ${total} 条记录`,
      size: 'small'
    }
  }

  formRef = React.createRef()

  // 完善信息
  fullInfo (data) {
    this.props.addWindow({ id: `AcceptCase-${data.id}`, title: `完善信息-${data.accept_no || data.serial_no}`, componentName: 'AcceptCase', forceRefresh: true, meta: { id: data.id } })
  }

  // 查看案件详情
  openDetail (data) {
    this.props.addWindow({ id: `CaseDetail-${data.id}`, title: `案件详情-${data.caseno_desc || data.acceptno_desc || data.case_no || data.accept_no || data.serial_no}`, componentName: 'CaseDetail', forceRefresh: true, meta: { id: data.id } })
  }

  // 前往重新指定秘书呈批
  toSelectSecretary (data) {
    this.props.addWindow({ id: `CaseDetail-${data.id}`, title: `案件详情-${data.caseno_desc || data.acceptno_desc || data.case_no || data.accept_no || data.serial_no}`, componentName: 'CaseDetail', forceRefresh: true, meta: { id: data.id, operate: 'processer_reassign' } })
  }

  // 改变案件状态
  changeStatus (status) {
    this.setState({
      status,
      pagination: {
        ...this.state.pagination,
        current: 1
      }
    }, () => {
      this.getTableData()
    })
  }

  // 获取案件数据
  getTableData (form) {
    form = form || this.formRef.current.getFieldsValue()
    const { pagination, status } = this.state
    const { current, pageSize } = pagination
    const condition = [{ k: 'status', o: 'not in', v: '未提交,已提交,收案,交费,已结案,已结案送达,已归档' }]
    this.setState({ loading: true })
    if (form.beginTime) {
      condition.push({ k: 'accept_datetime', o: '>=', v: Math.floor(moment(form.beginTime.format('YYYY-MM-DD')).valueOf() / 1000) })
    }
    if (form.endTime) {
      condition.push({ k: 'accept_datetime', o: '<=', v: Math.floor(moment(form.endTime.format('YYYY-MM-DD') + ' 23:59:59').valueOf() / 1000) })
    }
    if (form.caseno) {
      condition.push({ k: 'caseno_desc|counter_caseno_desc', o: 'like', v: `%${form.caseno}%` })
    }
    if (status === '紧急指定秘书') {
      condition.push({ k: 'emergency_processerid', o: 'not null' })
    }
    delete form.beginTime
    delete form.endTime
    this.$get('/api/xapc/case', {
      current,
      page_size: pageSize,
      condition: JSON.stringify(condition)
    }).then(res => {
      this.setState({ loading: false })
      if (res.status === 1) {
        this.setState({
          list: res.data.list.map((li, i) => {
            li.key = pageSize * (current - 1) + i + 1
            return li
          }),
          pagination: {
            ...pagination,
            total: res.data.total
          }
        })
      } else {
        return message.warning(res.message)
      }
    }).catch(() => this.setState({ loading: false }))
  }

  // 表格请求变化
  tableChange ({ current, pageSize }) {
    this.setState({
      pagination: {
        ...this.state.pagination,
        current,
        pageSize
      }
    }, () => {
      this.getTableData()
    })
  }

  // 重置表格
  resetHandle () {
    this.formRef.current.resetFields()
    this.setState({
      pagination: {
        ...this.state.pagination,
        current: 1
      }
    }, () => {
      this.getTableData()
    })
  }

  initFormByMeta () {
    const c = this.formRef.current
    const { formData = {} } = this.props.meta || {}
    c.resetFields()
    c.setFieldsValue(formData)
    c.submit()
  }

  componentDidUpdate (prev) {
    if (prev.meta !== this.props.meta) {
      this.initFormByMeta()
    }
  }

  componentDidMount () {
    this.initFormByMeta()
  }

  // 渲染搜索表单的展开和收起
  renderToggleBtns () {
    if (this.state.searchToggleBtn) {
      return (
        <Button type='link' onClick={() => { this.setState({ searchToggleBtn: !this.state.searchToggleBtn }) }}>
          <span>展开</span>
          <UpOutlined />
        </Button>
      )
    }
    return (
      <Button type='link' onClick={() => { this.setState({ searchToggleBtn: !this.state.searchToggleBtn }) }}>
        <span>收起</span>
        <DownOutlined />
      </Button>
    )
  }

  render () {
    const columns = getColumns.call(this)
    return (
      <div className={style.container}>
        <div className={style['title-line']}>
          <span>{this.props.title}</span>
        </div>
        <div className={style['search-container']}>
          <div className={style['search-form']}>
            <Form name='my_case_manage' {...layout} ref={this.formRef} onFinish={v => this.getTableData(v)}>
              <Row gutter={24}>
                <Col span={8}>
                  <Item label='案号' name='caseno'>
                    <Input placeholder='请输入案号' />
                  </Item>
                </Col>
                <Col span={8}>
                  <Item label='申请人' name='applicant'>
                    <Input placeholder='请输入申请人' />
                  </Item>
                </Col>
                <Col span={8}>
                  <Item label='被申请人' name='respondent'>
                    <Input placeholder='请输入被申请人' />
                  </Item>
                </Col>
              </Row>
              <Row gutter={24}>
                <Col span={8}>
                  <Item label='收案起始日期' name='beginTime'>
                    <DatePicker className={style.full} placeholder='请选择日期' />
                  </Item>
                </Col>
                <Col span={8}>
                  <Item label='收案截止日期' name='endTime'>
                    <DatePicker className={style.full} placeholder='请选择日期' />
                  </Item>
                </Col>
                <Col span={8}>
                  <Item>
                    <div className={style['search-btns']}>
                      <Button type='primary' ghost htmlType='submit'>搜索</Button>
                      <Button htmlType='reset' onClick={() => this.resetHandle()}>重置
                      </Button>
                      {/* {this.renderToggleBtns()} */}
                    </div>
                  </Item>
                </Col>
              </Row>
            </Form>
          </div>
        </div>
        <div className={style['table-btns-line']}>
          <div className={style['table-tabs-container']}>
            {/* <Radio.Group value={this.state.status} onChange={v => this.changeStatus(v.target.value)}>
              <Radio.Button value='全部'>全部</Radio.Button>
              <Radio.Button value='紧急指定秘书'>紧急指定秘书</Radio.Button>
            </Radio.Group> */}
          </div>
        </div>
        <div className={style['table-container']}>
          <Table loading={this.state.loading} columns={columns} dataSource={this.state.list} pagination={this.state.pagination} onChange={v => this.tableChange(v)} />
        </div>
      </div>
    )
  }
}

const mapState = mapStateToProps(function (state) {
  return {
    userInfo: state.basic.userInfo
  }
})

const mapDispatch = mapDispatchToProps(function (dispatch) {
  return {
    addWindow: (i) => dispatch(addWindow(i))
  }
})

export default connect(mapState, mapDispatch)(AllCaseManage)
